<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="稳定性方案">
        <template slot="btn">
          <el-button class="filter-item" type="primary" size="small" v-hasPermi="{v:['stability:create']}"
                     @click="handleCreate">创建
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <!-- 搜索 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" size="small">

        <el-form-item label="方案状态" style="margin-right:40px">
          <el-select v-model="queryParams.condition.stability_status" @change="handlStatus" placeholder="请选择方案状态">
            <el-option label="全部" :value="0"></el-option>
            <el-option label="回退修改" :value="-1"></el-option>
            <el-option label="已撤销" :value="-2"></el-option>
            <el-option label="草稿" :value="1"></el-option>
            <el-option label="审批中" :value="2"></el-option>
            <el-option label="已通过" :value="3"></el-option>
            <el-option label="变更中" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建人" style="margin-right:40px">
          <el-input v-model="queryParams.condition.creator_name" placeholder="请输入创建人" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>

        <el-form-item label="关键字" style="margin-right:40px">
          <el-input v-model="queryParams.condition.key_word" placeholder="请输入关键字" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery">搜索
          </el-button>
          <el-button plain size="small" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-form>

      <el-table :data="stabilityData" size="medium" border @row-click="aloneClick" :cell-style="cellStyle">
        <el-table-column prop="scheme_code" label="方案编号" align="center"/>

        <el-table-column prop="scheme_name" label="方案名称" header-align="center" :show-overflow-tooltip="true"/>

        <el-table-column prop="scheme_project_name" label="项目名称" :show-overflow-tooltip="true" header-align="center"/>

        <el-table-column prop="version_no" label="版本号" align="center"/>

        <el-table-column prop="creator_name" label="创建人" align="center"/>

        <el-table-column label="创建时间" align="center">
          <template #default="{row}">
            <span>{{ dateFormat1('yyyy-mm-dd HH:MM:SS',row.created_at) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="stability_status" label="状态" align="center">
          <template #default="{row}">
            <div v-if="row.stability_status === -1">
              <div>草稿</div>
              <div style="color: red">[ 回退修改 ]</div>
            </div>
            <div v-if="row.stability_status === -2">
              已撤销
            </div>
            <div v-if="row.stability_status === 1">
              草稿
            </div>
            <div v-else-if="row.stability_status === 2">
              审批中
            </div>
            <div v-else-if="row.stability_status === 3">
              已通过
            </div>
            <div v-else-if="row.stability_status === 4">
              <div>已通过</div>
              <div style="color: red">[ 变更中 ]</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" header-align="center" width="250">
          <template #default="{row}">
            <el-button type="text" size="medium" v-if="row.stability_status === 1 || row.stability_status === -1"
                       @click="handlEdit(row.id)">编辑
            </el-button>
            <el-button type="text" size="medium" v-if="row.stability_status === 1 || row.stability_status === -1"
                       @click="handlSubmit(row)">
              <span v-if="row.stability_scheme_type != 2">提交审批</span>
              <span v-else>提交变更审批</span>
            </el-button>
            <el-button type="text" size="medium"
                       v-if="row.stability_status === 3 && (row.creator_id === userInfo ||  row.project_leader_id === userInfo) "
                       @click="handlChange(row.id)">
              方案变更
            </el-button>
            <el-button type="text" size="medium"
                       v-if="row.stability_status === 3 && (row.creator_id === userInfo ||  row.project_leader_id === userInfo) "
                       @click="handlPrint(row)">
              打印
            </el-button>
            <el-button type="text " size="medium" v-if="row.scheme_check && row.scheme_check.Cancelable &&
            row.scheme_check.check_creator_id == userInfo " @click="cancelOperation(row)">撤销
            </el-button>
            <el-button type="text" size="medium" style="color:red"
                       v-if="row.stability_status === 1 || row.stability_status === -1 " @click="handlDeletet(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <!--页码-->
      <pagination style="display:flex;justify-content:flex-end;" :total="total" @pagination="pagination"
                  :page.sync="queryParams.pager.skip" :limit.sync="queryParams.pager.limit"/>

      <!--对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
                 :close-on-click-modal="false" v-if="open">
        <el-form ref="formOpen" :model="formOpen" :rules="rules" label-width="120px" size="small">
          <el-form-item label="审批结论" prop="stability_status">
            <el-radio-group v-model="formOpen.stability_status">
              <el-radio :label="3">通过</el-radio>
              <el-radio :label="-1">回退修改</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审批意见" prop="idea">
            <el-input v-model="formOpen.idea" type="textarea" placeholder="请输入审批意见"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="cancel">取 消</el-button>
          <el-button size="small" type="primary" @click="submitForm">
            确定
          </el-button>
        </div>
      </el-dialog>

      <el-dialog title="变更说明" :visible.sync="openChange" width="600px" append-to-body :before-close="cancelChange"
                 :close-on-click-modal="false" v-if="openChange">
        <el-form :model="openChangeForm" ref="openChangeForm" label-width="100px">
          <el-form-item label="变更原因" prop="change_reason"
                        :rules="[{ required: true, message: '请填写变更原因', trigger: 'blur' }]">
            <el-input type="textarea" v-model="openChangeForm.change_reason"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="cancelChange">取 消
          </el-button>
          <el-button size="small" type="primary" @click="submitChange">
            确 定
          </el-button>
        </div>
      </el-dialog>

      <!-- 打印稳定性方案 -->
      <vue-easy-print ref="printLookInfo" v-if="isShow">
        <template slot-scope="func">
          <div id="print" >
            <plan-print :data="data" />
          </div>
        </template>
      </vue-easy-print>
    </div>
  </div>
</template>

<script>
  import {
    stabilityList,
    subApproval,
    staDelete,
    approval,
    submitChange
  } from '@/api/stability/giveUp'
  import planPrint from '../print/index.vue'

  export default {
    components: {
      planPrint
    },
    data() {
      return {
        isShow:false,
        openChange: false,
        openChangeForm: {
          id: '',
          change_reason: ''
        },
        queryParams: {
          pager: {
            skip: 1,
            limit: 10
          },
          condition: {
            creator_name: '',
            stability_status: 0,
            key_word: ''
          }
        },
        total: 0,
        data:{},
        stabilityData: [],
        open: false,
        title: '',
        formOpen: {
          stability_status: undefined,
          idea: '',
          id: ''
        },
        rules: {
          stability_status: [
            { required: true, message: '请选择审批结论', trigger: 'change' }
          ],
          idea: [{ required: true, message: '请输入审批意见', trigger: 'blur' }]
        },
        userInfo: ''
      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {},
    //属性是手动定义的所需监听的值
    watch: {},

    beforeRouteEnter(to, from, next) {
      to.params.refresh = from.params.refresh
      next()
    },
    activated() {
      if (this.$route.params.refresh) {
        this.stabilityListData()
      }
    },
    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.userInfo = this.$store.getters.userInfo.user.id
      this.stabilityListData()
    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //创建
      handleCreate() {
        this.$router.push('/stability/giveUp/created')
      },

      //获取列表数据
      stabilityListData() {
        stabilityList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.stabilityData = res.data.data || []
            this.total = res.data.total
          }
        })
      },

      //页码
      pagination(val) {
        this.queryParams.pager.skip = val.page
        this.queryParams.pager.limit = val.limit
        this.stabilityListData()
      },

      handlStatus(val) {
        this.queryParams.condition.stability_status = val
        this.queryParams.pager.skip = 1
        this.stabilityListData()
      },

      //搜索
      handleQuery() {
        this.queryParams.pager.skip = 1
        this.stabilityListData()
      },
      //重置
      resetQuery() {
        this.queryParams = {
          pager: {
            skip: 1,
            limit: 10
          },
          condition: {
            creator_name: '',
            stability_status: 0,
            key_word: ''
          }
        }
        this.stabilityListData()
      },

      //编辑
      handlEdit(id) {
        this.$router.push({
          path: '/stability/giveUp/created',
          query: { id: id, type: 1 }
        })
      },

      //删除
      handlDeletet(id) {
        this.$confirm('确认删除吗？')
          .then(_ => {
            staDelete(id).then(res => {
              if (res.code === 200) {
                this.$message.success('删除成功')
                this.stabilityListData()
              }
            })
          })
          .catch(_ => {
          })
      },

      //提交审批
      handlSubmit(row) {
        let ssss = this.handlTree(row)
        if (ssss.boole) {
          this.$message.error(ssss.msg)
          return
        }
        // if (row.stability_instrument_infos.length === 0) {
        //   this.$message.error('请至少选择一个稳定性仪器')
        //   return
        // }
        if (row.stability_table_info === '') {
          this.$message.error('检查项目表明细表为空')
          return
        }
        if (row.stability_plan === '') {
          this.$message.error('稳定性试验放样信息表为空')
          return
        }
        let aaa = JSON.parse(row.stability_table_info) || {}
        let bbb = JSON.parse(row.stability_plan) || []
        let ccc = row.stability_details || []
        let selt = this
        let ddd = selt.handlTableCharm(aaa, ccc)
        if (!ddd) return
        let eee = selt.handlStableCharm(bbb)
        if (!eee) return
        let asd = ''
        this.$confirm('确认提交审批吗？')
          .then(_ => {
            if (row.stability_scheme_type == 2) {
              this.openChange = true
              this.openChangeForm.id = row.id
            } else {
              subApproval(row.id).then(res => {
                if (res.code === 200) {
                  selt.$message.success('提交成功')
                  selt.stabilityListData()
                }
              })
            }
          })
          .catch(_ => {
          })
      },

      //变更审核取消
      cancelChange() {
        this.openChangeForm = {
          id: '',
          change_reason: ''
        }
        this.openChange = false
      },

      //变更审核提交
      submitChange() {
        this.$refs.openChangeForm.validate(valid => {
          if (valid) {
            submitChange(this.openChangeForm).then(res => {
              if (res.code === 200) {
                this.$message.success('提交变更审批成功')
                this.$route.params.refresh = true
                this.$router.push('/stability/giveUp')
                this.cancelChange()
                this.stabilityListData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },

      //效验检查项目表明细
      handlTableCharm(val, arrList) {
        let aa, bb, cc, dd
        for (let key in val) {
          let dic = {}
          aa = key.split('?')
          let index = arrList.findIndex(a => a.stability_sample_info.id == aa[0])
          if (index !== -1) {
            bb = arrList[index].label
            let index1 = arrList[index].inspect_types.findIndex(
              a => a.inspect_type.id == aa[1]
            )
            if (index1 !== -1) {
              cc =
                arrList[index].inspect_types[index1].inspect_type
                  .inspect_type_name
              dd = bb + cc + '未勾选取样点'
            }
          }
          for (let i = 0; i < val[key].tableData.length; i++) {
            if (i !== val[key].tableData.length - 1) {
              let sss = val[key].tableData[i]
              let bo = false
              for (let obj in sss) {
                if (obj !== 'name' && obj !== 'num' && obj !== 'boole') {
                  let obj1 = obj.split('-')[0]
                  if (
                    val[key].headList === null ||
                    val[key].headList.length === 0
                  ) {
                    bo = true
                  } else {
                    let zzz = val[key].headList.findIndex(a => a == obj1)
                    if (zzz !== -1) {
                      if (typeof sss[obj] != 'string') {
                        if (!dic[obj] && typeof dic[obj] != 'bool') {
                          dic[obj] = false
                        }
                        if (sss[obj]) {
                          bo = true
                          dic[obj] = true
                          continue
                        }
                      }
                    }
                  }
                }
              }
              if (!bo) {
                this.$message.error(dd)
                return false
              }
            }
          }
          for (let a in dic) {
            if (!dic[a]) {
              this.$message.error(dd)
              return false
            }
          }
        }
        return true
      },

      //效验稳定性试验放样信息
      handlStableCharm(val) {
        for (let i = 0; i < val.length; i++) {
          let obj = val[i]
          for (let key in obj) {
            if (key.indexOf('使用倍数') != -1) {
              let sss = key.split('-')
              if (sss.length > 1 && obj[sss[1]] !== 0) {
                if (obj[key] == 0 || obj[key] == undefined) {
                  this.$message.error('样品统计使用倍数不能为0')
                  return false
                }
              }
            }
          }
        }
        return true
      },

      //验证tree
      handlTree(row) {
        var boole, msg
        if (row.sample_list == null) {
          msg = '请添加样品'
          boole = true
          return { boole: boole, msg: msg }
        }
        if (row.sample_list.length === 0) {
          msg = '请添加样品'
          boole = true
          return { boole: boole, msg: msg }
        } else {
          let aaa = row.stability_details
          if (aaa.length === 0) {
            msg = '请勾选样品'
            boole = true
            return { boole: boole, msg: msg }
          } else {
            for (let i = 0; i < aaa.length; i++) {
              let bbb = aaa[i].conditions
              if (bbb.length === 0) {
                msg = `请勾选${aaa[i].label}的考察类型`
                boole = true
                return { boole: boole, msg: msg }
              } else {
                for (let j = 0; j < bbb.length; j++) {
                  if (bbb[j].conditions.length === 0) {
                    msg = `请勾选${bbb[j].label}的放置条件`
                    boole = true
                    return { boole: boole, msg: msg }
                  }
                }
              }
            }
          }
        }
        return { boole: false }
      },

      //审批
      handlApproval(id) {
        this.open = true
        this.title = '审批流程'
        this.formOpen.id = id
      },

      //取消
      cancel() {
        this.open = false
        this.formOpen = {
          stability_status: undefined,
          idea: '',
          id: ''
        }
      },

      //审批确定
      submitForm() {
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            approval(this.formOpen).then(res => {
              if (res.code === 200) {
                this.$message.success('提交成功')
                this.stabilityListData()
                this.cancel()
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      //方案变更
      handlChange(id) {
        this.$router.push({
          path: '/stability/giveUp/created',
          query: { id: id, type: 2 }
        })
      },

      //单机行
      aloneClick(row, column, event) {
        if (column.label === '操作') {
          return
        }
        this.$router.push({
          path: '/stability/giveUp/details',
          query: { id: row.id, type: row.stability_status }
        })
      },

      cellStyle(data) {
        return 'cursor:pointer;'
      },
      //撤销审批
      cancelOperation(row) {
        const subdata = {
          flow_id: row.scheme_check.id,
          model_type: 'StabilityScheme'
        }
        this.$comFun
          .cancelFunc(subdata)
          .then(() => {
            this.$message({
              type: 'success',
              message: '已撤销'
            })
            this.stabilityListData()
          })
          .catch(err => {
            this.$message.error(err)
          })
      },

      //打印
      handlPrint(row) {
        this.data = JSON.parse(JSON.stringify(row))
        this.isShow = false
        setTimeout(()=>{
          this.isShow = true
        },100)
        setTimeout(() => {
          this.$refs.printLookInfo.print()
        }, 300)
      }
    }
  }
</script>
<style scoped>
  /* @import url(); 引入css类 */
  ::v-deep .el-button--text {
    padding: 0;
    margin: 0 !important;
    margin-right: 10px !important;
  }

</style>
